<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar
      class="my-nav-bar"
      title="登录"
      left-text="返回"
      right-text="按钮"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <van-form @submit="onSubmit">
      <!-- 输入框表单 -->
      <van-field
        v-model="phone"
        required
        label="手机号"
        type="tel"
        placeholder="请输入手机号"
        name="mobile"
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern:
              /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对',
          },
        ]"
      />
      <van-field
        v-model="password"
        required
        label="验证码"
        placeholder="请输入验证码"
        name="code"
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /\d{6}/, message: '验证码格式不对' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
//导入网络中间层
import { userLogin } from "@/views/user/user.js";
//导入token工具
import { saveToken } from "@/utils/token.js";

export default {
  data() {
    return {
      phone: "13912345678",
      password: "246810",
      isLoading: false,
    };
  },

  methods: {
    /*
      1. values 是一个对象
      2. key 是表单中输入元素的name属性
      3. 表单校验通过之后会触发的回调函数
    */
    onSubmit(values) {
      // console.log('submit', values)
      this.isLoading = true;
      //发送登录请求
      userLogin(values)
        .then((res) => {
          // console.log(res)
          this.$toast.success("登录成功");
          //登录成功之后，保存token
          saveToken(res.data.data);
          //跳转首页
          this.$router.go(-1);
        })
        .catch((err) => {
          this.$toast.success("账号或验证码错误");
        })
        .then(() => {
          //最后一个then，只要本次请求完成就会执行，不管是成功还是失败
          this.isLoading = false;
        });
    },
  },
};
</script>

<style lang="less">
.my-nav-bar {
  &.van-nav-bar {
    background-color: #3196fa;
  }

  .van-nav-bar__title {
    color: #fff;
  }

  .van-nav-bar__left {
    .van-icon-arrow-left,
    .van-nav-bar__text {
      color: #fff;
    }
  }
}
</style>
